package cn.stylefeng.guns.sys.modular.system.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.sys.core.listener.BtySfcListener;
import cn.stylefeng.guns.sys.core.util.DateUtil;
import cn.stylefeng.guns.sys.core.util.JsonResult;
import cn.stylefeng.guns.sys.modular.system.entity.BtyMdCaiwu;
import cn.stylefeng.guns.sys.modular.system.entity.BtyMdPsfymx;
import cn.stylefeng.guns.sys.modular.system.entity.BtyMdSfc;
import cn.stylefeng.guns.sys.modular.system.mapper.BtyBrandMapper;
import cn.stylefeng.guns.sys.modular.system.mapper.BtyMdCaiwuMapper;
import cn.stylefeng.guns.sys.modular.system.mapper.BtyMdSfcMapper;
import cn.stylefeng.guns.sys.modular.system.model.params.BtyMdCaiwuParam;
import cn.stylefeng.guns.sys.modular.system.model.params.BtyMdSfcParam;
import cn.stylefeng.guns.sys.modular.system.model.result.*;
import cn.stylefeng.guns.sys.modular.system.service.BtyBrandService;
import cn.stylefeng.guns.sys.modular.system.service.BtyMdCaiwuService;
import cn.stylefeng.guns.sys.modular.system.service.BtyMdPsfymxService;
import cn.stylefeng.guns.sys.modular.system.service.BtyMdSfcService;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ErrorResponseData;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.alibaba.excel.EasyExcel;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static java.util.stream.Collectors.toList;


/**
 * 收发存控制器
 *
 * @author 
 * @Date 2021-10-25 11:24:44
 */
@Controller
@RequestMapping("/btyMdSfc")
public class BtyMdSfcController extends BaseController {

    private String PREFIX = "/modular/system/btyMdSfc";

    @Autowired
    private BtyMdSfcService btyMdSfcService;
    @Autowired
    private BtyMdCaiwuService btyMdCaiwuService;
    @Autowired
    private BtyMdPsfymxService btyMdPsfymxService;
    @Autowired
    private BtyBrandMapper btyBrandMapper;
    @Autowired
    private BtyBrandService btyBrandService;
    @Autowired
    private BtyMdCaiwuMapper btyMdCaiwuMapper;

    /**
     * 跳转到主页面
     *
     * @author 
     * @Date 2021-10-25
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "/btyMdSfc.html";
    }

    /**
     * 新增页面
     *
     * @author 
     * @Date 2021-10-25
     */
    @RequestMapping("/add")
    public String add() {
        return PREFIX + "/btyMdSfc_add.html";
    }

    /**
     * 编辑页面
     *
     * @author 
     * @Date 2021-10-25
     */
    @RequestMapping("/edit")
    public String edit() {
        return PREFIX + "/btyMdSfc_edit.html";
    }

    /**
     * 新增接口
     *
     * @author 
     * @Date 2021-10-25
     */
    @RequestMapping("/addItem")
    @ResponseBody
    public ResponseData addItem(BtyMdSfcParam btyMdSfcParam) {
        this.btyMdSfcService.add(btyMdSfcParam);
        return ResponseData.success();
    }

    /**
     * 编辑接口
     *
     * @author 
     * @Date 2021-10-25
     */
    @RequestMapping("/editItem")
    @ResponseBody
    public ResponseData editItem(BtyMdSfcParam btyMdSfcParam) {
        this.btyMdSfcService.update(btyMdSfcParam);
        return ResponseData.success();
    }

    /**
     * 删除接口
     *
     * @author 
     * @Date 2021-10-25
     */
    @RequestMapping("/delete")
    @ResponseBody
    public ResponseData delete(BtyMdSfcParam btyMdSfcParam) {
        this.btyMdSfcService.delete(btyMdSfcParam);
        return ResponseData.success();
    }

    /**
     * 查看详情接口
     *
     * @author 
     * @Date 2021-10-25
     */
    @RequestMapping("/detail")
    @ResponseBody
    public ResponseData detail(BtyMdSfcParam btyMdSfcParam) {
        BtyMdSfc detail = this.btyMdSfcService.getById(btyMdSfcParam.getBtyMdSfcId());
        return ResponseData.success(detail);
    }

    /**
     * 查询列表
     *
     * @author 
     * @Date 2021-10-25
     */
    @ResponseBody
    @RequestMapping("/list")
    public LayuiPageInfo list(BtyMdSfcParam btyMdSfcParam) {
        return this.btyMdSfcService.findPageBySpec(btyMdSfcParam);
    }

    /**
     * 导入配送费用明细
     */
    @RequestMapping("/importPsfymx1")
    @ResponseBody
    public ResponseData importPsfymx1(@RequestParam("file") MultipartFile file) {
        ResponseData data = new ResponseData();
        try {
            data = this.btyMdCaiwuService.importPsfymx(file);
        } catch (Exception e) {
            e.printStackTrace();
            return ErrorResponseData.error("导入失败！");
        }
        return data;
    }

    /**
     * 导入配送费用明细
     */
    @RequestMapping("/importPsfymx")
    @ResponseBody
    public ResponseData importPsfymx(@RequestParam("file") MultipartFile file) {
        try {
            //文件名
            String fileName = file.getOriginalFilename();

            if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
                throw new Exception("上传文件格式不正确");
            }
            boolean isExcel2003 = true;
            if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
                isExcel2003 = false;
            }

            InputStream is = file.getInputStream();
            Workbook wb = null;
            if (isExcel2003) {
                wb = new HSSFWorkbook(is);
            } else {
                wb = new XSSFWorkbook(is);
            }

            //excel中多个sheet表，获取所有sheet表的数量
            //int sheets = wb.getNumberOfSheets();
            //TODO-1 默认就一个sheet
            Sheet sheet = wb.getSheetAt(0);

            //获取当前月的上个月份
            String lastMonth = DateUtil.getLastMonth();//yyyyMM
            String lastMonthStr = DateUtil.getLastMonthStr();//YYYY-MM
            List<Map<Object, Object>> list = new ArrayList<Map<Object, Object>>();

            //TODO-5 获取第四行以下字段和内容
            for (int r = 4; r <= sheet.getLastRowNum() - 1; r++) {
                Row row = sheet.getRow(r);
                if (row == null) {
                    continue;
                }
                Map<Object, Object> map = new HashMap<>();

                map.put("sx",r+1);//行号

                //循环单元格cell
                for (int cellNum = 0; cellNum <= row.getLastCellNum(); cellNum++) {
                    Cell cell = row.getCell(cellNum);
                    //把单元格的内容转换为字符串
                    if (cell != null) {
                        cell.setCellType(CellType.STRING);
                        map.put(cellNum, cell.getStringCellValue());
                    }
                }

                list.add(map);
            }

            List<BtyMdCaiwu> shopList = new ArrayList<>();
            List<BtyMdPsfymx> psfyList = new ArrayList<>();
            List<Long> cwIdList = new ArrayList<>();

            //循环取出的数据
            for (Map map : list) {

                Integer sx = map.get("sx") == null ? null : Integer.valueOf(map.get("sx").toString());//行号

                String className = map.get(0) == null ? "" : map.get(0).toString();//存货分类名称
                String shopName = map.get(1) == null ? "" : map.get(1).toString();//部门
                String goodName = map.get(4) == null ? "" : map.get(4).toString();//存货名称
                String goodSpec = map.get(5) == null ? "" : map.get(5).toString();//存货规格
                String unit = map.get(6) == null ? "" : map.get(6).toString();//计量单位
                BigDecimal enterNum = (map.get(7) == null || map.get(7) == "") ? BigDecimal.ZERO.setScale(2, BigDecimal.ROUND_HALF_UP) : new BigDecimal(map.get(7).toString()).setScale(2, BigDecimal.ROUND_HALF_UP);//进货数据
                BigDecimal returnNum = (map.get(8) == null || map.get(8) == "") ? BigDecimal.ZERO.setScale(2, BigDecimal.ROUND_HALF_UP) : new BigDecimal(map.get(8).toString()).setScale(2, BigDecimal.ROUND_HALF_UP);//退货数量
//                BigDecimal enterMoney = (map.get(10) == null || map.get(10) == "") ? BigDecimal.ZERO : new BigDecimal(map.get(10).toString());//进货金额
                BigDecimal enterMoney = (map.get(10) == null || map.get(10) == "") ? BigDecimal.ZERO.setScale(2, BigDecimal.ROUND_HALF_UP) : new BigDecimal(map.get(10).toString()).setScale(2, BigDecimal.ROUND_HALF_UP);//进货金额
                BigDecimal returnMoney = (map.get(11) == null || map.get(11) == "") ? BigDecimal.ZERO.setScale(2, BigDecimal.ROUND_HALF_UP) : new BigDecimal(map.get(11).toString()).setScale(2, BigDecimal.ROUND_HALF_UP);//退货金额

                if (ToolUtil.isEmpty(shopName)){
                    return ResponseData.error("第" + sx + "行数据没有店名！");
                }
                //查询该店妖码
                String yaoma = btyBrandService.getYmList(shopName);
                if (ToolUtil.isEmpty(yaoma)){
                    return ResponseData.error(shopName + "没有妖码！");
                }
                Long btyMdCaiwuId = Long.valueOf(lastMonth + yaoma);

                BtyMdCaiwu btyMdCaiwuParam = new BtyMdCaiwu();
                btyMdCaiwuParam.setBtyMdCaiwuId(btyMdCaiwuId);//财务id
                btyMdCaiwuParam.setYaoma(yaoma);//妖码
                btyMdCaiwuParam.setDm(shopName);//门店名
                btyMdCaiwuParam.setKjqj(lastMonthStr);//会计月
                btyMdCaiwuParam.setFlagPsfymx(1);//存在配送费用明细数据
                if(!shopList.contains(btyMdCaiwuParam)){
                    shopList.add(btyMdCaiwuParam);
                    cwIdList.add(btyMdCaiwuId);
                }

                BtyMdPsfymx btyMdPsfymx = new BtyMdPsfymx();
                btyMdPsfymx.setSx(sx);//行号
                btyMdPsfymx.setGoodName(goodName);//存货名称
                btyMdPsfymx.setGoodSpec(goodSpec);//存货规格
                btyMdPsfymx.setShopName(shopName);//部门
                btyMdPsfymx.setClassName(className);//存货分类名称
                btyMdPsfymx.setEnterNum(enterNum);//进货数据
                btyMdPsfymx.setReturnNum(returnNum);//退货数量
                btyMdPsfymx.setEnterMoney(enterMoney);//进货金额
                btyMdPsfymx.setUnit(unit);//计量单位
                btyMdPsfymx.setReturnMoney(returnMoney);//退货金额
                btyMdPsfymx.setBtyMdCaiwuId(btyMdCaiwuId);//财务id

                psfyList.add(btyMdPsfymx);
            }
            // TODO-5 保存之前删除之前存入的当月数据
            this.btyMdCaiwuMapper.deleteCaiWuAndPsmxData(lastMonthStr,lastMonth);

            //TODO-6 财务表中写入数据
            //财务表中是否存在
            List<BtyMdCaiwu> list1 = btyMdCaiwuMapper.getCw(cwIdList);
            if (ToolUtil.isNotEmpty(list1)){//存在 则修改状态
                //批量修改财务表中存在的数据
                btyMdCaiwuMapper.updateCwPs(list1);

                List<BtyMdCaiwu> list2 = new ArrayList<>();
                //获取财务表中没有的数据
                shopList.forEach(btyMdCaiwu -> {
                    if (list1.stream().filter(w->w.getBtyMdCaiwuId().equals(btyMdCaiwu.getBtyMdCaiwuId())).findAny().isPresent()) {
                        list2.add(btyMdCaiwu);
                    }
                });
                // 差集 (shopList - list2)
                List<BtyMdCaiwu> list3 = shopList.stream().filter(item -> !list2.contains(item)).collect(toList());

                //每60条保存一次
                for(int i = 0; i < list3.size();){
                    int i2 = (i + 60);
                    i2 = i2 > list3.size() ? list3.size() : i2;
                    List<BtyMdCaiwu> sub = list3.subList(i, i2);
                    btyMdCaiwuMapper.insertCwPs(sub);
                    i = i2;
                }
            }else {//不存在 则新增数据
                //每60条保存一次
                for(int i = 0; i < shopList.size();){
                    int i2 = (i + 60);
                    i2 = i2 > shopList.size() ? shopList.size() : i2;
                    List<BtyMdCaiwu> sub = shopList.subList(i, i2);
                    btyMdCaiwuMapper.insertCwPs(sub);
                    i = i2;
                }
            }

            //TODO-6 配送费用明细表写入数据
            if (CollectionUtil.isNotEmpty(psfyList)){
                //每90条保存一次
                for(int i = 0; i < psfyList.size();){
                    int i2 = (i + 90);
                    i2 = i2 > psfyList.size() ? psfyList.size() : i2;
                    List<BtyMdPsfymx> sub = psfyList.subList(i, i2);
                    this.btyMdCaiwuService.savePsfymx(sub, shopList, cwIdList);
                    i = i2;
                }
            }

            //TODO-7 删除主表中没有资产负债表数据和利润表数据的主表数据
            this.btyMdCaiwuMapper.deleteCaiWuData(lastMonthStr);

        } catch (Exception e) {
            e.printStackTrace();
            return ErrorResponseData.error("导入失败！");
        }
        return ResponseData.success();
    }

    /**
     * 导入收发存
     */
    @RequestMapping("/importSfc1")
    @ResponseBody
    public ResponseData importSfc1(@RequestParam("file") MultipartFile file) {
        ResponseData data = new ResponseData();
        try {
            data = this.btyMdCaiwuService.importSfc(file);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseData.success();
    }

    @RequestMapping("/importSfc")
    @ResponseBody
    public ResponseData importSfc(@RequestParam("file") MultipartFile file) {
        ResponseData data = new ResponseData();
        try {
            //文件名
            String fileName = file.getOriginalFilename();

            if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
                throw new Exception("上传文件格式不正确");
            }
            boolean isExcel2003 = true;
            if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
                isExcel2003 = false;
            }

            InputStream is = file.getInputStream();
            Workbook wb = null;
            if (isExcel2003) {
                wb = new HSSFWorkbook(is);
            } else {
                wb = new XSSFWorkbook(is);
            }

            //excel中多个sheet表，获取所有sheet表的数量
            //int sheets = wb.getNumberOfSheets();
            //TODO-1 默认就一个sheet
            Sheet sheet = wb.getSheetAt(0);

            //获取当前月的上个月份
            String lastMonth = DateUtil.getLastMonth();//yyyyMM
            String lastMonthStr = DateUtil.getLastMonthStr();//YYYY-MM
            List<Map<Object, Object>> list = new ArrayList<Map<Object, Object>>();

            //TODO-5 获取第四行以下的门店及字段和内容
            for (int r = 4; r <= sheet.getLastRowNum(); r++) {
                Row row = sheet.getRow(r);
                if (row == null) {
                    continue;
                }
                Map<Object, Object> map = new HashMap<>();

                map.put("sx",r+1);//行号

                //循环单元格cell
                for (int cellNum = 0; cellNum <= row.getLastCellNum(); cellNum++) {
                    Cell cell = row.getCell(cellNum);
                    //把单元格的内容转换为字符串
                    if (cell != null) {
                        cell.setCellType(CellType.STRING);
                        map.put(cellNum, cell.getStringCellValue());
                    }
                }

                list.add(map);
            }

            List<BtyMdCaiwu> shopList = new ArrayList<>();
            List<BtyMdSfc> sfcList = new ArrayList<>();
            List<Long> cwIdList = new ArrayList<>();

            //循环取出的数据
            for (Map map : list) {

                Integer sx = map.get("sx") == null ? null : Integer.valueOf(map.get("sx").toString());//行号

                String yaoma = map.get(0) == null ? "" : map.get(0).toString();//妖码
                String shopName = map.get(1) == null ? "" : map.get(1).toString();//部门
                String className = map.get(5) == null ? "" : map.get(5).toString();//存货分类名称
                String goodName = map.get(7) == null ? "" : map.get(7).toString();//存货名称
                String goodSpec = map.get(8) == null ? "" : map.get(8).toString();//存货规格
                String unit = map.get(9) == null ? "" : map.get(9).toString();//计量单位
                BigDecimal qcNum = (map.get(10) == null || map.get(10) == "") ? BigDecimal.ZERO : new BigDecimal(map.get(10).toString());//期初数量
                BigDecimal qcPrice = (map.get(11) == null || map.get(11) == "") ? BigDecimal.ZERO.setScale(4, BigDecimal.ROUND_HALF_UP) : new BigDecimal(map.get(11).toString()).setScale(4, BigDecimal.ROUND_HALF_UP);//期初单价
                BigDecimal qcMoney = (map.get(12) == null || map.get(12) == "") ? BigDecimal.ZERO.setScale(2, BigDecimal.ROUND_HALF_UP) : new BigDecimal(map.get(12).toString()).setScale(2, BigDecimal.ROUND_HALF_UP);//期初金额
                BigDecimal srNum = (map.get(13) == null || map.get(13) == "") ? BigDecimal.ZERO : new BigDecimal(map.get(13).toString());//收入数量
                BigDecimal srPrice = (map.get(14) == null || map.get(14) == "") ? BigDecimal.ZERO.setScale(4, BigDecimal.ROUND_HALF_UP) : new BigDecimal(map.get(14).toString()).setScale(4, BigDecimal.ROUND_HALF_UP);//收入单价
                BigDecimal srMoney = (map.get(15) == null || map.get(15) == "") ? BigDecimal.ZERO.setScale(2, BigDecimal.ROUND_HALF_UP) : new BigDecimal(map.get(15).toString()).setScale(2, BigDecimal.ROUND_HALF_UP);//收入金额
                BigDecimal fcNum = (map.get(16) == null || map.get(16) == "") ? BigDecimal.ZERO : new BigDecimal(map.get(16).toString());//发出数量
                BigDecimal fcPrice = (map.get(17) == null || map.get(17) == "") ? BigDecimal.ZERO.setScale(4, BigDecimal.ROUND_HALF_UP) : new BigDecimal(map.get(17).toString()).setScale(4, BigDecimal.ROUND_HALF_UP);//发出单价
                BigDecimal fcMoney = (map.get(18) == null || map.get(18) == "") ? BigDecimal.ZERO.setScale(2, BigDecimal.ROUND_HALF_UP) : new BigDecimal(map.get(18).toString()).setScale(2, BigDecimal.ROUND_HALF_UP);//发出金额
                BigDecimal jcNum = (map.get(19) == null || map.get(19) == "") ? BigDecimal.ZERO : new BigDecimal(map.get(19).toString());//结存数量
                BigDecimal jcPrice = (map.get(20) == null || map.get(20) == "") ? BigDecimal.ZERO.setScale(4, BigDecimal.ROUND_HALF_UP) : new BigDecimal(map.get(20).toString()).setScale(4, BigDecimal.ROUND_HALF_UP);//结存单价
                BigDecimal jcMoney = (map.get(21) == null || map.get(21) == "") ? BigDecimal.ZERO.setScale(2, BigDecimal.ROUND_HALF_UP) : new BigDecimal(map.get(21).toString()).setScale(2, BigDecimal.ROUND_HALF_UP);//结存金额

                if (ToolUtil.isEmpty(shopName)){
                    return ResponseData.error("第" + sx + "行数据没有店名！");
                }
                //查询该店妖码
//                String yaoma = btyBrandService.getYmList(shopName);
//                if (ToolUtil.isEmpty(yaoma)){
//                    return ResponseData.error(shopName + "没有妖码！");
//                }
                if (yaoma.contains(".")){
                    yaoma = yaoma.substring(0, 7);
                }
                Long btyMdCaiwuId = Long.valueOf(lastMonth + yaoma);

                BtyMdCaiwu btyMdCaiwu = new BtyMdCaiwu();
                btyMdCaiwu.setBtyMdCaiwuId(btyMdCaiwuId);//财务id
                btyMdCaiwu.setYaoma(yaoma);//妖码
                btyMdCaiwu.setDm(shopName);//门店名
                btyMdCaiwu.setKjqj(lastMonthStr);//会计月
                btyMdCaiwu.setFlagSfc(1);//存在收发存数据
                if(!shopList.contains(btyMdCaiwu)){
                    shopList.add(btyMdCaiwu);
                    cwIdList.add(btyMdCaiwuId);
                }

                BtyMdSfc btyMdSfc = new BtyMdSfc();
                btyMdSfc.setSx(sx);//行号
                btyMdSfc.setGoodName(goodName);//存货名称
                btyMdSfc.setGoodSpec(goodSpec);//存货规格
                btyMdSfc.setShopName(shopName);//部门
                btyMdSfc.setClassName(className);//存货分类名称
                btyMdSfc.setUnit(unit);//计量单位
                btyMdSfc.setQcNum(qcNum);//期初数量
                btyMdSfc.setQcPrice(qcPrice);//期初单价
                btyMdSfc.setQcMoney(qcMoney);//期初金额
                btyMdSfc.setSrNum(srNum);//收入数量
                btyMdSfc.setSrPrice(srPrice);//收入单价
                btyMdSfc.setSrMoney(srMoney);//收入金额
                btyMdSfc.setFcNum(fcNum);//发出数量
                btyMdSfc.setFcPrice(fcPrice);//发出单价
                btyMdSfc.setFcMoney(fcMoney);//发出金额
                btyMdSfc.setJcNum(jcNum);//结存数量
                btyMdSfc.setJcPrice(jcPrice);//结存单价
                btyMdSfc.setJcMoney(jcMoney);//结存金额
                btyMdSfc.setBtyMdCaiwuId(btyMdCaiwuId);//财务id

                sfcList.add(btyMdSfc);
            }

            // TODO-5 保存之前删除之前存入的当月数据
            this.btyMdCaiwuMapper.deleteCaiWuAndSfcData(lastMonthStr,lastMonth);

            //TODO-6 财务表中写入数据
            //财务表中是否存在
            List<BtyMdCaiwu> list1 = btyMdCaiwuMapper.getCw(cwIdList);
            if (ToolUtil.isNotEmpty(list1)){//存在 则修改状态
                //批量修改财务表中存在的数据
                btyMdCaiwuMapper.updateCw(list1);

                List<BtyMdCaiwu> list2 = new ArrayList<>();
                //获取财务表中没有的数据
                shopList.forEach(btyMdCaiwu -> {
                    if (list1.stream().filter(w->w.getBtyMdCaiwuId().equals(btyMdCaiwu.getBtyMdCaiwuId())).findAny().isPresent()) {
                        list2.add(btyMdCaiwu);
                    }
                });
                // 差集 (shopList - list2)
                List<BtyMdCaiwu> list3 = shopList.stream().filter(item -> !list2.contains(item)).collect(toList());

                //每60条保存一次
                for(int i = 0; i < list3.size();){
                    int i2 = (i + 60);
                    i2 = i2 > list3.size() ? list3.size() : i2;
                    List<BtyMdCaiwu> sub = list3.subList(i, i2);
                    btyMdCaiwuMapper.insertCw(sub);
                    i = i2;
                }
            }else {//不存在 则新增数据
                //每60条保存一次
                for(int i = 0; i < shopList.size();){
                    int i2 = (i + 60);
                    i2 = i2 > shopList.size() ? shopList.size() : i2;
                    List<BtyMdCaiwu> sub = shopList.subList(i, i2);
                    btyMdCaiwuMapper.insertCw(sub);
                    i = i2;
                }
            }

            //TODO-6 收发存表写入数据
            if (CollectionUtil.isNotEmpty(sfcList)){
                //每90条保存一次
                for(int i = 0; i < sfcList.size();){
                    int i2 = (i + 90);
                    i2 = i2 > sfcList.size() ? sfcList.size() : i2;
                    List<BtyMdSfc> sub = sfcList.subList(i, i2);
                    this.btyMdCaiwuService.saveSfc(sub, shopList, cwIdList);
                    i = i2;
                }
            }

            //TODO-7 删除主表中没有资产负债表数据和利润表数据的主表数据
            this.btyMdCaiwuMapper.deleteCaiWuData(lastMonthStr);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseData.success();
    }

    /**
     * 导入excel- 收发存
     */
    @RequestMapping("/addUsers")
    @ResponseBody
    public ResponseData addUsers(@RequestParam("file") MultipartFile file) throws IOException {
        this.btyMdCaiwuService.addUsersInputStreamAsync(file.getInputStream());
//        JsonResult jsonResult = new JsonResult();
//
//        //获取当前月的上个月份
//        String lastMonth = DateUtil.getLastMonth();//yyyyMM
//        String lastMonthStr = DateUtil.getLastMonthStr();//YYYY-MM
//        //保存之前删除之前存入的当月数据
//        this.btyMdCaiwuMapper.deleteCaiWuAndSfcData(lastMonthStr,lastMonth);
//
//        try {
//            BtySfcListener btySfcListener = new BtySfcListener(btyMdSfcService);
//            EasyExcel.read(file.getInputStream(), BtySfcDto.class, btySfcListener).sheet(0).headRowNumber(4).doRead();
//
//            //导入成功之后 删除主表中没有资产负债表数据和利润表数据的主表数据
//            this.btyMdCaiwuMapper.deleteCaiWuData(lastMonthStr);
//
//        }catch (Exception e) {
//            e.printStackTrace();
//            jsonResult.setState(0);
//            jsonResult.setErrmsg(e.getMessage());
//            return jsonResult;
//        }
        return ResponseData.success(true);
    }

    /**
     * 点击查看配送费用明细表
     *
     */
    @RequestMapping("/viewPsfymx")
    public String viewPsfymx(Model model, BtyMdCaiwuParam param) {
        model.addAttribute("param", param);
        return "/modular/system/btyMdCaiwu/btyMdCaiwu_viewPsfymx.html";
    }

    /**
     * 配送费用明细
     *
     */
    @ResponseBody
    @RequestMapping(value = "/findAllPsfymx", method = RequestMethod.GET)
    public LayuiPageInfo findAllPsfymx(BtyMdCaiwuParam param) {
        List<BtyMdPsfymxResult> detail = this.btyMdPsfymxService.findAllPsfymx(param);
        int total = detail.size();
        LayuiPageInfo layuiPageInfo = new LayuiPageInfo();
        layuiPageInfo.setData(detail);
        layuiPageInfo.setCount(total);
        return layuiPageInfo;
    }

    /**
     * app查询-配送费用明细
     *
     */
    @ResponseBody
    @RequestMapping(value = "/findPsfymxDate", method = RequestMethod.GET)
    public ResponseData findPsfymxDate(BtyMdCaiwuParam param) {

        if (StringUtils.isBlank(param.getYaoma())) {
            return ResponseData.error(412, "请求失败，妖码不能为空");
        }
        if (StringUtils.isBlank(param.getKjqj())) {
            return ResponseData.error(412, "请求失败，会计月不能为空");
        }

        List<BtyMdPsfymxResult> detail = this.btyMdPsfymxService.findAllPsfymx(param);

        return ResponseData.success(detail);
    }

    /**
     * 点击查看配送收发存表
     *
     */
    @RequestMapping("/viewSfc")
    public String viewSfc(Model model, BtyMdCaiwuParam param) {
        model.addAttribute("param", param);
        return "/modular/system/btyMdCaiwu/btyMdCaiwu_viewSfc.html";
    }

    /**
     * 收发存
     *
     */
    @ResponseBody
    @RequestMapping(value = "/findAllSfc", method = RequestMethod.GET)
    public LayuiPageInfo findAllSfc(BtyMdCaiwuParam param) {
        return this.btyMdPsfymxService.findAllSfc(param);
    }

    /**
     * app查询-收发存
     *
     */
    @ResponseBody
    @RequestMapping(value = "/findSfcDate", method = RequestMethod.GET)
    public ResponseData findSfcDate(BtyMdCaiwuParam param) {

        if (StringUtils.isBlank(param.getYaoma())) {
            return ResponseData.error(412, "请求失败，妖码不能为空");
        }
        if (StringUtils.isBlank(param.getKjqj())) {
            return ResponseData.error(412, "请求失败，会计月不能为空");
        }

        List<BtyMdSfcResult> detail = this.btyMdPsfymxService.findSfcDate(param);

        return ResponseData.success(detail);
    }
}


